package com.kuaimacode.kframework.agent.controller.order;

import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.agent.services.address.AddressService;
import com.kuaimacode.kframework.agent.services.master.MasterOrderAccitityService;
import com.kuaimacode.kframework.agent.services.master.MasterService;
import com.kuaimacode.kframework.agent.services.order.OrderService;
import com.kuaimacode.kframework.agent.services.user.UserService;
import com.kuaimacode.kframework.agent.util.SessionUtil;
import com.kuaimacode.kframework.agent.vo.request.OrderReq;
import com.kuaimacode.kframework.common.Constant;
import com.kuaimacode.kframework.common.JsonResult;
import com.kuaimacode.kframework.component.ComponentUtil;
import com.kuaimacode.kframework.constants.PageConstants;
import com.kuaimacode.kframework.mybatis.models.master.MasterOrderAccitity;
import com.kuaimacode.kframework.mybatis.models.master.UserMaster;
import com.kuaimacode.kframework.mybatis.models.user.Address;
import com.kuaimacode.kframework.mybatis.models.user.Order;
import com.kuaimacode.kframework.mybatis.models.user.User;
import com.kuaimacode.kframework.util.DictUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author 中元
 * @date 2019/03/18
 */

/**
 * Controller
 */
@Controller
@RequestMapping({"/order"})
public class OrderController {
	private static String PAGE_FILE_NAME = "order/";

	@Autowired
	private OrderService orderServices;
	@Autowired
	private MasterOrderAccitityService accitityService;
	@Autowired
	private AddressService addressService;
	@Autowired
	private MasterService masterService;
	@Autowired
	private UserService userService;
	@Autowired
	private ComponentUtil componentUtil;


	@RequestMapping(value = {"/index"})
	public String index(
			@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
			@RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize,
			OrderReq order, ModelMap model) {
		//需要取当前分站id
		order.setAgentId(SessionUtil.getAgentId());
		PageInfo<Order> pageInfo = orderServices.findAll(pageNum, pageSize, order);
		// pageInfo.list order
		model.put("pageInfo", pageInfo);
		model.put("orderSearch", order);
		return PAGE_FILE_NAME + "index";
	}


	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(ModelMap map) {
		Order order = new Order();
		map.put("order", order);
		map.put("isAdd", true);
		return PAGE_FILE_NAME+"form";
	}


	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@PathVariable String id, ModelMap map) {
		Order order = orderServices.getById(id);
		map.put("order", order);
		map.put("isAdd", false);
		return PAGE_FILE_NAME+"form";
	}

	@RequestMapping(value = {"/edit"}, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult edit(Order order, Boolean isAdd,ModelMap map) {
		try {
			if(isAdd){
				// 新建保存
				orderServices.save(order);
			}else{
				// 编辑保存
				orderServices.updateById(order);
			}
		} catch (Exception e) {
			return JsonResult.failure(e.getMessage());
		}
		return JsonResult.success();
	}

	@RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
	public String detail(@PathVariable String id, ModelMap map) {
		Order order = orderServices.getById(id);

		//查询当前订单的流程状态
		MasterOrderAccitity accitity = accitityService.getMasterAccititysByOrderId(order.getId(), null);
		map.put("accitity", accitity);

		//师傅信息
		if(order.getMasterId() != null){
			UserMaster master = masterService.findByUserId(order.getMasterId());
			if(master != null){
				map.put("master", master);
				User user = userService.getById(master.getUserId());
				if(user != null){
					map.put("masterPhone", user.getPhone());
				}
			}
		}

		//用户电话
		User user = null;
		if(order.getUserId() != null){
			user = userService.getById(order.getUserId());
			if(user != null){
				map.put("user", user);
				map.put("userPhone", user.getPhone());
			}
		}

		if(order.getHasPartner() == 1){
			//处理合作商家地址
			Address fromAddress = new Address();
			if(user != null){
				fromAddress.setName(user.getPartnerName());
				//fromAddress.setTitle(user.getPartnerAddress());
				fromAddress.setPhone(user.getPartnerPhone());
				fromAddress.setDetail(user.getPartnerAddress());
				map.put("fromAddress", fromAddress);
			}
		}else{
			if(order.getFromAddressId() !=null){
				//查询地址
				Address fromAddress = addressService.getById(order.getFromAddressId());
				map.put("fromAddress", fromAddress);
			}
			if(order.getToAddressId() !=null){
				//查询地址
				Address toAddress = addressService.getById(order.getToAddressId());
				map.put("toAddress", toAddress);
			}
		}

		/*if(order.getFromAddressId() !=null){
			//查询地址
			Address fromAddress = addressService.getById(order.getFromAddressId());
			map.put("fromAddress", fromAddress);
		}
		if(order.getToAddressId() !=null){
			//查询地址
			Address toAddress = addressService.getById(order.getToAddressId());
			map.put("toAddress", toAddress);
		}*/
		//完成时间
		if(order.getStatus() == Constant.OrderStatusEnum.WAIT_EVLAUTE.getCode() ||
				order.getStatus() == Constant.OrderStatusEnum.OK.getCode()){
			map.put("finishTime", order.getUpdateAt());
		}else{
			map.put("finishTime", null);
		}
		//完成订单方式
		map.put("finishStatus", getCodeDesc(order.getFinishStatus()));
		//到达起点方式
		map.put("operatorOrigin", getCodeDesc(order.getOperatorOrigin()));
		//到达终点方式
		map.put("operatorFinal", getCodeDesc(order.getOperatorFinal()));

		//处理图片
		if(order.getImages() != null){
			//处理图片
			List<String> images = new ArrayList<String>();
			Arrays.stream(Optional.ofNullable(order.getImages()).get().split(",")).forEach(o->{
				images.add(componentUtil.convertImgUrl(o));
			});
			map.put("images", images);
		}
		if(order.getGoodsImages() != null){
			//处理图片
			List<String> images = new ArrayList<String>();
			Arrays.stream(Optional.ofNullable(order.getGoodsImages()).get().split(",")).forEach(o->{
				images.add(componentUtil.convertImgUrl(o));
			});
			map.put("goodsImages", images);
		}
		if(order.getType() != 1 && accitity != null){
			//技术服务类型查询服务计时
			if ("2".equals(order.getPriceWay())){
				if (accitity.getStartTime()==null){
					map.put("serverTimes", 0);
				}else{
					Date endTime = accitity.getEndTime()==null?new Date():accitity.getEndTime();
					Date startDate = accitity.getStartTime();
					String serverTimes = String.valueOf(new BigDecimal(String.valueOf((endTime.getTime()-startDate.getTime())/1000)).setScale(1,BigDecimal.ROUND_HALF_DOWN));
					map.put("serverTimes", serverTimes);
				}
			}else{
				map.put("serverTimes", 0);
			}
		}
		map.put("order", order);
		return PAGE_FILE_NAME+"detail";
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult delete(@PathVariable String id, ModelMap map) {
		try {
			orderServices.removeById(id);
		} catch (Exception e) {
			return JsonResult.failure(e.getMessage());
		}
		return JsonResult.success();
	}

	/**
	 * 查询订单子类型
	 * @param parentCode
	 * @return
	 */
	@RequestMapping(value = {"/getChildType/{parentCode}"}, method = RequestMethod.GET)
	@ResponseBody
	public JsonResult getChildTypeList(@PathVariable String parentCode) {
		Map<String,String> map = DictUtil.keyValueByPCodeList(Constant.SERVICE_CLASS_DICT_NAME,parentCode);
		return JsonResult.success(map);
	}

	/**
	 *
	 * @param code
	 * @return
	 */
	private static String getCodeDesc(Integer code){
		if(code == null){
			return "";
		}
		if(0 ==code){
			return "正常";
		}else if(1== code){
			return "强制";
		}else{
			return "";
		}
	}
}
